<template>
  <div class="app-container">
    <el-card shadow="never" v-loading="loading">
      <el-row :gutter="5">
        <el-col :span="24" class="main-card-view">
          <el-row v-if="userInfo.roleName != '专家'">
            <el-card shadow="never" class="top-search-view-card">
              <el-row>
                <el-form :inline="true" ref="searchForm" :model="searchForm" class="demo-form-inline search-view">
                  <el-form-item label="专家名称" prop="name">
                    <el-input v-model="searchForm.name" placeholder="请输入"></el-input>
                  </el-form-item>
                  <el-form-item label="专家电话" prop="telNum">
                    <el-input v-model="searchForm.telNum" placeholder="请输入"></el-input>
                  </el-form-item>
                  <el-form-item label="机构名称" prop="organName">
                    <el-input v-model="searchForm.organName" placeholder="请输入"></el-input>
                  </el-form-item>
                  <el-form-item label="状态" prop="status">
                    <el-input v-model="searchForm.status" placeholder="请输入" style="width: 100px;"></el-input>
                  </el-form-item>
                  <el-form-item label="是否开放" prop="opened">
                    <el-input v-model="searchForm.opened" placeholder="请输入" style="width: 100px;"></el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="handleSearch" class="search-button">查询</el-button>
                    <el-button type="success" @click="handleReset" class="reset-button">重置</el-button>
                   <!-- <el-button type="primary" @click="showCreateDialog" class="new-button" >添加
                    </el-button> -->
                  </el-form-item>
                  <el-form-item v-if="userInfo.roleName === '运营人员' || userInfo.roleName === '管理员'">
                    <el-button type="primary" @click="excExport" class="search-button">导出</el-button>
                  </el-form-item>
                </el-form>
              </el-row>
            </el-card>
          </el-row>

          <el-row>
            <el-card shadow="never">
              <el-table :data="tableData" :stripe="true" style="width: 100%" @selection-change="selectionChange">
                <el-table-column type="selection" align="center" />
                <el-table-column prop="personalImg" align="center" label="图片">
                  <template slot-scope="scope">
                    <el-image :src="scope.row.personalImg" style="width: 50px;height: 50px;" />
                  </template>
                </el-table-column>
                <el-table-column prop="name" align="center" label="专家名称" />
                <el-table-column prop="telNum" align="center" label="专家电话" />
                <el-table-column prop="organName" align="center" label="机构名称" />
                <el-table-column prop="departmentName" align="center" label="科室" />
                <el-table-column prop="position" align="center" label="职称" />
                <!-- <el-table-column prop="officePhone" align="center" label="电话" /> -->
                <el-table-column prop="dependency" align="center" label="等级" />
                <el-table-column prop="status" align="center" label="状态" />
                <el-table-column prop="opened" align="center" label="是否开放" />
                <el-table-column align="center" label="操作" width="300">
                  <template slot-scope="scope">


                   <!-- <el-button type="text" @click="uploadPdf(scope.row.uid)">上传pdf</el-button> -->
                   <el-button type="text" @click="loadPdf(scope.row)">下载pdf</el-button>
                  <!-- <x-upload v-model="form.coverFileName" /> -->
                    <!--编辑-->
                   <el-button type="text"  @click="handleDelete(scope.row)" v-if="userInfo.roleName === '运营人员' || userInfo.roleName === '管理员'">删除 </el-button>

                     <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-if="userInfo.roleName === '运营人员' || userInfo.roleName === '管理员'">
                       <el-button size="mini" type="text">是否开放</el-button>
                       <el-dropdown-menu slot="dropdown">
                         <el-dropdown-item command="openedTrue" >是</el-dropdown-item>
                         <el-dropdown-item command="openedFalse">否</el-dropdown-item>
                       </el-dropdown-menu>
                     </el-dropdown>


                  </template>
                </el-table-column>

              </el-table>
              <XPagination ref="pageInfo" :total="total" :get-data="getList" />
            </el-card>
          </el-row>
        </el-col>
      </el-row>
    </el-card>
    <el-dialog width="80%" :title="dialogTitle" :visible.sync="dialogVisible">
      <el-form label-width="150px" ref="form" :model="form" :rules="formRules">
        <el-tabs>
          <el-tab-pane label="专家基本信息" />
        </el-tabs>
        <el-row>
          <el-col :span="10">
            <el-form-item label="专家名称" prop="name">
              <el-input v-model="form.name" />
            </el-form-item>
            <el-form-item label="属地" prop="dependency">
              <el-select style="width: 100%;" v-model="form.dependency">
                <el-option v-for="(item, index) in ['省级', '市级', '区县级']" :key="index" :label="item" :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item label="职称" prop="position">
              <el-select style="width: 100%;" v-model="form.position">
                <el-option v-for="(item, index) in positionList" :key="index" :label="item.name" :value="item.name" />
              </el-select>
            </el-form-item>
            <el-form-item label="办公电话" prop="officePhone">
              <el-input v-model="form.officePhone" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="区域" prop="expertType">
              <el-cascader ref="expertType" v-model="expertType" :options="regionOptions" placeholder="请选择地区"
                :props="props" @change="expertTypeChange"></el-cascader>
            </el-form-item>
            <el-form-item label="机构名称" prop="organName">
              <el-input v-model="form.organName">
                <template slot="append">
                  <el-button @click="openOrgList">选择机构</el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="性别" prop="sex">
              <el-select v-model="form.sex" style="width: 100%;">
                <el-option :label="'男'" value="男"></el-option>
                <el-option :label="'女'" value="女"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="个人图像" prop="personalImg">
              <x-upload v-model="form.personalImg" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="擅长" prop="beGoodAt">
              <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 6 }" v-model="form.beGoodAt" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="关联科室" prop="departmentName">
              <el-select style="width: 100%;" v-model="form.departmentName">
                <el-option v-for="(item, index) in departmentList" :key="index" :label="item.name" :value="item.name" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="简介" prop="briefIntroduction">
              <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 6 }" v-model="form.briefIntroduction" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template slot="footer">
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>


    <el-dialog title="专家信息" :visible.sync="dialogTableVisible" width="85%">
      <el-card shadow="never" v-loading="loading">
        <el-row :gutter="5">
          <el-col :span="24" class="main-card-view">
            <el-row>
              <el-card shadow="never" class="top-search-card">
                <el-row>
                  <el-form :inline="true" :model="searchOrgForm" class="demo-form-inline search-view">
                    <el-form-item label="机构名称">
                      <el-input v-model="searchOrgForm.organName" placeholder="请输入机构名称"></el-input>
                    </el-form-item>
                    <el-form-item label="级别">
                     <el-select style="width: 100%;" v-model="searchForm.grade" clearable>
                       <el-option v-for="(item) in gradeList" :key="item.uid" :label="item.name" :value="item.name" />
                     </el-select>
                    </el-form-item>

                    <el-form-item>
                      <el-button type="primary" @click="handleOrgSearch" class="search-button">
                        查询
                      </el-button>
                    </el-form-item>
                  </el-form>
                </el-row>
              </el-card>
            </el-row>

            <el-row>
              <el-card shadow="never">
                <el-table :data="tableOrgData" :stripe="true" style="width: 100%">
                  <el-table-column prop="classification" align="center" label="机构分类" />
                  <el-table-column prop="organName" align="center" label="机构名称" />
                  <el-table-column prop="grade" align="center" label="级别" />
                  <el-table-column prop="phone" align="center" label="电话" />
                  <el-table-column prop="area" align="center" label="区域">
                    <template slot-scope="scope">
                      {{ [scope.row.province, scope.row.city, scope.row.area].join(">") }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="dependency" align="center" label="等级"/>
                  <el-table-column align="center" label="操作" width="200">
                    <template slot-scope="scope">
                      <el-button type="text" @click="selectOrg(scope.$index, scope.row)">选择
                      </el-button><!--编辑-->
                    </template>
                  </el-table-column>
                </el-table>
                <XPagination ref="orgPageInfo" :total="orgTotal" :get-data="getOrgList" />
              </el-card>
            </el-row>
          </el-col>
        </el-row>
      </el-card>
    </el-dialog>
    <el-dialog width="40%" title="修改密码" :visible.sync="dialogPwsVisible">
      <el-form label-width="150px" ref="form" :model="form" :rules="formRules">

        <el-form-item label="登录账户" prop="logName">
          <el-input v-model="form.logName" />
        </el-form-item>
        <el-form-item label="密码" prop="pwd">
          <el-input v-model="form.pwd" type="password" />
        </el-form-item>
        <el-form-item label="确认密码" prop="pwd">
          <el-input v-model="form.verifyPwd" type="password" />
        </el-form-item>
      </el-form>
      <template slot="footer">
        <el-button type="primary" @click="passwordSave">保存</el-button>
      </template>
    </el-dialog>
    <el-dialog width="40%" title="专家资料下载" :visible.sync="attachmentsDialog">
            <el-table :data="attachmentsList" :stripe="true" style="width: 100%">
                <el-table-column prop="originName" align="center" label="专业图片" />
                <el-table-column align="center" label="操作" width="200">
                    <template slot-scope="scope">
                        <el-button @click="download(scope.row)" type="text">下载</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <template slot="footer">
                <el-button type="primary" @click="attachmentsDialog = false">关闭</el-button>
            </template>
        </el-dialog>
  </div>
</template>

<script>
import XPagination from "../../components/xpagination/XPagination";
import * as expertInfo from "../../api/expertInfo"
import * as formUtils from "../../utils/formUtils"
import XUpload from "../../components/xupload/XUpload";
import * as myDownload from "../../api/myDownload"
import * as organInfo from "../../api/organInfo";
import * as dictionaryInfo from "../../api/dictionaryInfo"
import * as areaInfo from "../../api/areaInfo"
import uploadAttachments from "../../components/uploadAttachments.vue"
import XLSX from 'xlsx';
export default {
  name: "list",
  components: { XUpload, XPagination,uploadAttachments,myDownload },
  data () {
    return {
      selectionData: [],
      searchForm: {
        name: "",
        telNum:"",
        status: "",
        opened: "",
      },
      gradeList: [],
      tableData: [],
      loading: false,
      dialogVisible: false,
      userInfo: {},
      total: 0,
      dialogTitle: "添加专家资料",
      form: {
        uid: "",
        name: "",
        idNum: "",
        organName: "",
        organUid: "",
        expertType: "",
        personalImg: "",
        sex: "",
        birthday: "",
        nation: "",
        politicalOutlook: "",
        educationLevel: "",
        graduationInstitution: "",
        workUnit: "",
        majorStudied: "",
        highestEducationLevel: "",
        highestDegree: "",
        profession: "",
        duties: "",
        position: "",
        serviceYears: "",
        officePhone: "",
        telNum: "",
        appointmentTime: "",
        email: "",
        beGoodAt: "",
        personalSpecialty: "",
        workAddress: "",
        wechatAccount: "",
        tiktokAccount: "",
        otherAccount: "",
        mailAddress: "",
        departmentName: "",
        departmentUid: "",
        briefIntroduction: "",
        logName: "",
        pwd: "",
        status: "",
        province: "",
        city: "",
        area: "",
        organLevel: "",
        organClassify: "",
        grade: "",
        verifyPwd:""
      },
      editStatus: "add",
      formRules: {
        name: [
          { required: true, message: '不能为空', trigger: 'blur' },
        ],
        organName: [
          { required: true, message: '不能为空', trigger: 'blur' },
        ],
        idNum: [
          { required: true, message: '不能为空', trigger: 'blur' },
        ],
        expertType: [
          { required: true, message: '不能为空', trigger: 'blur' },
        ],
        personalImg: [
          { required: true, message: '不能为空', trigger: 'blur' },
        ],
        sex: [
          { required: true, message: '不能为空', trigger: 'blur' },
        ],
        nation: [
          { required: true, message: '不能为空', trigger: 'blur' },
        ],

        logName: [
          { required: true, message: '不能为空', trigger: 'blur' },
        ],
        pwd: [
          { required: true, message: '不能为空', trigger: 'blur' },
          {
                  type: 'string',
                  message: '请输入不包含空格的字符',
                  trigger: 'blur',
                  transform(value) {
                    if (value && value.indexOf(' ') === -1) {
                      return value
                    } else {
                      return false
                    }
                  }
                },
                {
                  trigger: 'blur',
                  message: '密码必须由数字、字母、特殊字符组合,请输入6-16位',
                  validator: (rule, value, callback) => {
                    var passwordreg = /(?=.*\d)(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{6,16}/
                    if (!passwordreg.test(value)) {
                      callback(new Error('密码必须由数字、字母、特殊字符组合,请输入6-16位'))
                    }else{
                      callback()
                    }
                  }
                }
        ],
        verifyPwd: [
          { required: true, message: '不能为空', trigger: 'blur' },
          {
                  type: 'string',
                  message: '请输入不包含空格的字符',
                  trigger: 'blur',
                  transform(value) {
                    if (value && value.indexOf(' ') === -1) {
                      return value
                    } else {
                      return false
                    }
                  }
                },
                {
                  trigger: 'blur',
                  message: '密码必须由数字、字母、特殊字符组合,请输入6-16位',
                  validator: (rule, value, callback) => {
                    var passwordreg = /(?=.*\d)(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{6,16}/
                    if (!passwordreg.test(value)) {
                      callback(new Error('密码必须由数字、字母、特殊字符组合,请输入6-16位'))
                    }else{
                      callback()
                    }
                  }
                }
        ],
      },
      expertTypeList: ["省级专家", "市级专家", "县级专家"],
      positionList: ["主治医师"],
      departmentList: ["医学影像科", "基础医学、临床医学"],
      expertType: '',
      // 机构管理信息
      dialogTableVisible: false,
      searchOrgForm: {
        creditIdentifier: "",
        grade: "",
        organName: "",
        unitName: "",
      },
      tableOrgData: [],
      orgTotal: 0,
      regionOptions: [],
      props: {
        children: "childs",
        label: "areaName",
        checkStrictly: true,
        value: "areaName",
        emitPath: true
      },
      dialogPwsVisible: false,
      attachmentsDialog:false,
      attachmentsList:[]
    }
  },
  methods: {
      handleReset(){
          this.$refs.searchForm.resetFields();
      },
      handleCommand(command, row) {
        switch (command) {
          case "openedTrue":
            this.setOpened(row,'是');
            break;
          case "openedFalse":
            this.setOpened(row, '否');
            break;
          default:
            break;
        }
      },

      setOpened(row,opened){
          row.opened=opened;
          row.mailAddress='0'//其实代表，只保存，不需要更新审批流程
          expertInfo.update(row);
      },
    selectionChange (data) {
      this.selectionData = data
    },
    excExport(){
        let sheetData = []
        let datas=[]
        if(this.selectionData.length>0){
            datas=this.selectionData
        }else{
            datas=this.tableData
        }
        sheetData = datas.map(item => ({
            '专家名称': item.name,
            '推荐单位': item.organName,
            '工作单位': item.workUnit||item.organName,
            '科室': item.departmentName,
            '职务': item.position,
            '电话': item.telNum||item.officePhone,
            '等级': item.dependency,
            '状态': item.status,
        }))
        const wb = XLSX.utils.book_new();
        const ws = XLSX.utils.json_to_sheet(sheetData);
        XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
        XLSX.writeFile(wb, 'user_data.xlsx');
    },
    exportPdf(uid){
        expertInfo.exportPdfById(uid).then(response=>{
            if(response.data.code==200 && response.data.data.fileUrl){
                const a = document.createElement('a')
                a.style.display = 'none'
                a.download = response.data.data.originName
                if(!response.data.data.fileUrl.includes("https")){
                    response.data.data.fileUrl=response.data.data.fileUrl.replace('http','https');
                }
                a.href = response.data.data.fileUrl
                document.body.appendChild(a)
                a.click()
                document.body.removeChild(a)
            }else{
                 this.$message.error("无pdf文件")
            }
        })
    },
    loadPdf (data) {
        if(!data.highestEducationLevel){
            this.$message.error("无pdf文件")
            return;
        }
        this.form = Object.assign({}, data)
        this.attachmentsDialog = true
        expertInfo.queryFileInf({ fileUrl: data.highestEducationLevel }).then(result => {
            this.attachmentsList = result.data.data.rows
            console.log("data.uid-->"+this.attachmentsList)
        }).catch(error => {
            this.$message.error(error)
            console.log(error)
        })
    },
    download (data) {
        const a = document.createElement('a')
        a.style.display = 'none'
        a.download = data.originName
        a.href = data.fileUrl
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)

    },
    getList (pageInfo) {
      const param = {
        ...this.searchForm,
        ...pageInfo
      }
      let userInfo = JSON.parse(localStorage.getItem("user_info"))
      if('专家'==userInfo.roleName){
          param.uid=userInfo.uid
      }
      if(userInfo.roleName==='机构'){
          param.organUid=userInfo.uid


      }
      expertInfo.queryByPage(param).then(response => {
        console.log(response)
        this.tableData = response.data.data.rows
        this.total = response.data.data.total
        this.loading = false
      }).catch(error => {
        console.log(error)
      })
    },


    handleDelete (data) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const param = {
          uid: data.uid,
        }
        this.loading = true
        expertInfo.deleteById(param).then(result => {
          this.loading = false
          this.$message.success(result.data.msg)
          this.handleSearch()
        }).catch(error => {
          this.loading = false
          console.log(error)
        })
      }).catch(() => {
        console.log('取消删除')
      });
    },

    handleSearch () {
      this.$refs.pageInfo.loadData()
    },
    showCreateDialog () {
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.dialogTitle = "添加专家资料"
        this.editStatus = "add"
        this.$refs.form.resetFields()
        this.form = Object.assign({}, this.$options.data().form)
        this.expertType = []
      })
    },
    handleSave () {
      if (this.editStatus === "add") {
        this.handleAdd()
      } else {
        this.handleEdit()
      }
    },
    handleAdd () {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return false
        }
        const param = Object.assign({}, this.form)
        formUtils.filterFormFields(param)
        expertInfo.insert(param).then(result => {
          this.$message.success(result.data.msg)
          this.dialogVisible = false
          this.handleSearch()
        }).catch(error => {
          this.$message.error(error)
          console.log(error)
        })

      })
    },
    handleEdit () {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return false
        }
        const param = Object.assign({}, this.form)
        formUtils.filterFormFields(param)
        expertInfo.update(param).then(result => {
          this.$message.success(result.data.msg)
          this.dialogVisible = false
          this.dialogPwsVisible = false
          this.handleSearch()
        }).catch(error => {
          this.$message.error(error)
          console.log(error)
        })
      })
    },
    showEditDialog (index, data) {
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.form.resetFields()
        this.form = Object.assign({}, data)
        this.expertType = this.form.expertType.split('/')
        this.dialogTitle = "编辑专家资料"
        this.editStatus = "edit"
      })
    },
    uploadDialog (index, data) {
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.form.resetFields()
        this.form = Object.assign({}, data)
        this.expertType = this.form.expertType.split('/')
        this.dialogTitle = "编辑专家资料"
        this.editStatus = "edit"
      })
    },
    getGradeList () {
      dictionaryInfo.queryDictionary({
        lastDict: "jigou-03"
      }).then(response => {
        this.gradeList = response.data.data.rows
        this.gradeList.sort((a, b) => {
          return a.sort - b.sort
        })
      }).catch(error => {
        console.log(error)
      })
      dictionaryInfo.queryDictionary({
        lastDict: "jigou-02"
      }).then(response => {
        this.businessNatureList = response.data.data.rows
        this.gradeList.sort((a, b) => {
          return a.sort - b.sort
        })
      }).catch(error => {
        console.log(error)
      })
    },
    // 机构管理信息
    getOrgList (pageInfo) {
      const param = {
        ...this.searchOrgForm,
        ...pageInfo
      }
      organInfo.queryByPage(param).then(response => {
        console.log(response)
        this.tableOrgData = response.data.data.rows
        this.orgTotal = response.data.data.total
        this.loading = false
      }).catch(error => {
        console.log(error)
      })
    },
    handleOrgSearch () {
      this.$refs.orgPageInfo.loadData()
    },

    openOrgList () {
      this.getOrgList();
      this.dialogTableVisible = true;
    },
    selectOrg (index, data) {
      console.log(data)
      this.form.organName = data.organName;
      this.form.organUid = data.uid;
      this.form.organClassify = data.classification;
      this.form.grade = data.grade;
      this.dialogTableVisible = false;
    },
    getPositionList () {
      dictionaryInfo.queryDictionary({
        lastDict: "zhicheng"
      }).then(response => {
        this.positionList = response.data.data.rows
        this.positionList.sort((a, b) => {
          return a.sort - b.sort
        })
      }).catch(error => {
        console.log(error)
      })
      dictionaryInfo.queryDictionary({
        lastDict: "keshi"
      }).then(response => {
        this.departmentList = response.data.data.rows
        this.departmentList.sort((a, b) => {
          return a.sort - b.sort
        })
      }).catch(error => {
        console.log(error)
      })
    },
    getData () {
      areaInfo.queryTree({}).then(result => {
        this.regionOptions = result.data.data;
        this.regionOptions = this.buildTree(this.regionOptions)
      }).catch(error => {
        console.log(error);
      })
    },
    buildTree (tree) {
      tree.forEach(item => {
        if (item.childs && item.childs.length > 0) {
          item.childs = this.buildTree(item.childs);
        } else if (item.childs && item.childs.length === 0) {
          delete item.childs;
        }
      });
      return tree;
    },
    expertTypeChange (e) {
      this.form.expertType = e.join('/')
      this.$refs.expertType.dropDownVisible = false
    },
    showPwsDialog (index, data) {
      this.dialogPwsVisible = true
      this.form = {
        uid: data.uid,
        logName: data.logName,
      }
    },
    passwordSave () {
      if (this.form.verifyPwd === this.form.pwd) {
        this.handleEdit()
      } else {
        this.$message.error('两次密码不同！！！')
      }
    }
  },
  mounted () {
    this.userInfo = JSON.parse(localStorage.getItem('user_info'))
    this.handleSearch()
    this.getPositionList()
    this.getGradeList()
    this.getData()
  }
}
</script>

<style scoped lang="scss"></style>
